//
//  LocationErrorViewController.m
//  OperationPro
//
//  Created by yaxue wang on 2017/2/28.
//  Copyright © 2017年 展鸿科技. All rights reserved.
//

#import "LocationErrorViewController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "ScreentoneViewController.h"
#import "MapViewController.h"
@interface LocationErrorViewController ()<BMKMapViewDelegate, BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UITextViewDelegate>
{
    BMKLocationService* _locService;
    BMKGeoCodeSearch *_geocodesearch;
    double longitude;
    double latitude;
    BOOL isGeoSearch;
    NSString* _cityName;
    NSString* _province;

    //机构
    NSString *_uuid;
    UITextView *_textField;
}
@property(nonatomic,strong)UILabel *trameLab;

@end

@implementation LocationErrorViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    latitude=1;
    longitude=1;
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    //编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _geocodesearch.delegate = self;//设置代理为self
    

    [self setTitle:@"机构位置错误"];
    UILabel *destrideLab=[[UILabel alloc]initWithFrame:CGRectMake(15, 25+64, WindowWidth-30, 30)];
    destrideLab.text=@"请在身处网点时进行报错。";
    destrideLab.font=F(14);
    destrideLab.textColor=FontColor;
    [self.view addSubview:destrideLab];
    UILabel *postionLab=[[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(destrideLab.frame)+10, 80, 15)];
    postionLab.text=@"选择机构";
    postionLab.font=F(14);
    postionLab.textColor=FontColor;
    [self.view addSubview:postionLab];
    _trameLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(postionLab.frame), CGRectGetMaxY(destrideLab.frame)+10,  WindowWidth-CGRectGetMaxX(postionLab.frame), 15)];
    _trameLab.text=@"请选择";
    _trameLab.font=F(14);
    _trameLab.textColor=MainColor;
    [self.view addSubview:_trameLab];
    _trameLab.userInteractionEnabled=YES;
    
    [_trameLab bk_whenTapped:^{
        if([_trameLab.text isEqualToString:@"请选择"])
        {
            //没有开启定位的时候
            ScreentoneViewController *screentVC=[[ScreentoneViewController alloc]init];
            NSMutableDictionary *dic1=[[NSMutableDictionary alloc]init];
            [dic1 setObject:[NSNumber numberWithDouble:1]  forKey:@"latitude"];
            [dic1 setObject:[NSNumber numberWithDouble:1] forKey:@"longitude"];
            screentVC.dataDic=dic1;
            screentVC.backuiud=^(NSMutableDictionary*dict){
                
                _trameLab.text =[dict objectForKey:@"name"];
                _uuid =[dict objectForKey:@"uuid"];
                longitude=[[dict objectForKey:@"longitude"]doubleValue];
                latitude=[[dict objectForKey:@"latitude"]doubleValue];

            };
            
            [self pushController:screentVC];
            
        }else
        {
            ScreentoneViewController *screentVC=[[ScreentoneViewController alloc]init];
            NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
            [dic setObject:[NSNumber numberWithDouble:latitude]  forKey:@"latitude"];
            [dic setObject:[NSNumber numberWithDouble:longitude]  forKey:@"longitude"];
            screentVC.dataDic=dic;
            screentVC.backuiud=^(NSMutableDictionary*dic1){
                
                _trameLab.text =[dic1 objectForKey:@"name"];
                _uuid =[dic1 objectForKey:@"uuid"];
                longitude=[[dic1 objectForKey:@"longitude"]doubleValue];
                latitude=[[dic1 objectForKey:@"latitude"]doubleValue];
            };
            
            [self pushController:screentVC];
            
            
        }
    }];
    UILabel *adressLab=[[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(_trameLab.frame)+15, 80, 15)];
    adressLab.text=@"详细地址";
    adressLab.font=F(14);
    adressLab.textColor=FontColor;
    [self.view addSubview:adressLab];
     _textField=[[UITextView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(adressLab.frame), CGRectGetMaxY(_trameLab.frame)+10, WindowWidth-CGRectGetMaxX(adressLab.frame)-15, 40)];
    _textField.layer.borderColor=LineColor.CGColor;
    _textField.layer.borderWidth=0.5;
    _textField.delegate=self;
    _textField.backgroundColor=[UIColor whiteColor];
    _textField.font=F(14);
    [self.view addSubview:_textField];
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(28,CGRectGetMaxY(_textField.frame)+30, WindowWidth-56, 42);
    [self.view addSubview:button];
    [button setBackgroundColor:MainColor];
    button.layer.masksToBounds=YES;
    button.layer.cornerRadius=4;
    [button setTitle:@"打开地理位置" forState:UIControlStateNormal];
    button.titleLabel.font =F(16);
    [button bk_addEventHandler:^(id sender) {
        if (latitude ==1) {
            [CClass showMessage:@"请选择机构"];
            return ;
        }
        MapViewController*mapVC =[[MapViewController alloc]init];
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        [dic setObject:[NSNumber numberWithDouble:latitude]  forKey:@"latitude"];
        [dic setObject:[NSNumber numberWithDouble:longitude]  forKey:@"longitude"];
        mapVC.dataDic=dic;
        NSLog(@"======%@",dic);

        [mapVC setBackLocation:^(NSDictionary *dataDic) {
            NSLog(@"======%@",dataDic);
            _textField.text=[dataDic objectForKey:@"subtitle"];
        }];
        [self pushController:mapVC];

    } forControlEvents:UIControlEventTouchUpInside];

}
#pragma mark 定位
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //关闭地位
    
    
    [self onClickReverseGeocode];
    [_locService stopUserLocationService];
}
-(void)onClickReverseGeocode  //发送反编码请求的.
{
    isGeoSearch = false;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};//初始化
    if (_locService.userLocation.location.coordinate.longitude!= 0
        && _locService.userLocation.location.coordinate.latitude!= 0) {
        //如果还没有给pt赋值,那就将当前的经纬度赋值给pt
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude
        };
    }
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;//设置反编码的店为pt
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//发送反编码请求.并返回是否成功
    if(flag)
    {
        echo(@"反geo检索发送成功");
    }
    else
    {
        echo(@"反geo检索发送失败");
    }
}
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    
        _cityName = result.addressDetail.city;
        _province = result.addressDetail.province;
    for (int i = 0; i < result.poiList.count; i++) {
        
        BMKPoiInfo* poi = [result.poiList objectAtIndex:i];
        if (i==0) {
            //            _locationLab.text = poi.name;
            latitude= poi.pt.latitude;
            longitude = poi.pt.longitude;
#pragma mark 机构请求
            NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
            [dic setObject:[NSNumber numberWithDouble:longitude] forKey:@"longitude"];
            [dic setObject:[NSNumber numberWithDouble:latitude] forKey:@"latitude"];
            [CClass HttpRequestTask:YES withUrl:@"select_showInstSelect" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
                NSMutableArray *ar=[model.B_data objectForKey:@"list"];
                NSDictionary *dic =[ar objectAtIndex:0];
                _uuid=[dic objectForKey:@"uuid"];
                _trameLab.text=[dic objectForKey:@"name"];
                
                
            } onError:^(BaseModel *model) {
                
            }];
            
        }
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)textViewDidBeginEditing:(UITextView *)textView{

        if ([textView.text isEqualToString:@"描述问题或分享经验..."]) {
            [textView setText:@""];
            [textView setTextColor:C(@"585858")];
        }
    
    
}
- (void)textViewDidChange:(UITextView *)textView{
    
    
            //移除表情
        if ([CClass stringContainsEmoji:textView.text]) {
            textView.text=[textView.text substringToIndex:textView.text.length-2];
            return;
        }
        
        if (textView.markedTextRange == nil && textView.text.length > 20)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
            
        {
            
            textView.text = [textView.text substringToIndex:20];
            
        }
        
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
        if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
            return NO;
        }
        

    return YES;
    
}



@end
